const Koa = require('koa'); // Koa 为一个class
const Router = require('koa-router') // koa 路由中间件
const bodyParser = require('koa-bodyparser'); // 处理post请求，把 koa2 上下文的表单数据解析到 ctx.request.body 中
const app = new Koa();
const router = new Router(); // 实例化路由
const fs = require('fs-extra')

app.use(bodyParser())

router.post('/file', async (ctx, next) => {
  const { enData, zhData } = ctx.request.body
  if(!enData){
    ctx.response.body = {
      code: -1,
      message: 'en data error',
      data: enData
    }
    return
  }
  if(!zhData){
    ctx.response.body = {
      code: -1,
      message: 'zh data error',
      data: zhData
    }
    return
  }
  const enFile = `export default ${JSON.stringify(enData, null, '\n')}`
  const zhFile = `export default ${JSON.stringify(zhData, null, '\n')}`
  try {
    await fs.emptyDir('./lang')
    await fs.emptyDir('E:/work/erp_web/src/lang/financial')
    await fs.outputFile('./lang/en.js', enFile)
    await fs.outputFile('./lang/zh.js', zhFile)
    await fs.outputFile('E:/work/erp_web/src/lang/financial/en.js', enFile)
    await fs.outputFile('E:/work/erp_web/src/lang/financial/zh.js', zhFile)
  } catch (err) {
    console.log(err)
    ctx.response.body = {
      code: 0,
      message: 'error',
      data: err
    }
    return
  }
  ctx.response.body = {
    code: 0,
    message: 'write file suceess',
    data: []
  }
})

app.use(router.routes());

app.listen(3333, () => {
  console.log('This server is running at http://localhost:' + 3333)
})
